// ==========================================================================
// 所属模块：DevGenTables
// 生成日期：2024-02-20 21:43:27 +0800 CST
// 生成路径: apps/system/function.js
// 生成人：xScript_Engine
// 数据表：dm_tables - DevGenTables
// ==========================================================================

TABLE_NAME = 'dm_tables';
COLUMN_KEY = 'table_id';
TABLE_FIELDS = '*';

'use api/lib/sql.js';

function getPlaceholders(condition) {
	const columnsArr = Object.keys(condition);
	const placeholders = [];
	const tempParams = [];
	columnsArr.forEach((item) => {
		if (item == 'tableName') {
			placeholders.push(`table_name LIKE ?`);
			tempParams.push('%' + condition[item] + '%');
		} else if (item == 'tableId') {
			placeholders.push(`table_id = ?`);
			tempParams.push(condition[item]);
		} else if (item == 'tableComment') {
			placeholders.push(`table_comment LIKE ?`);
			tempParams.push('%' + condition[item] + '%');
		}
	});

	return {
		placeholders: placeholders.join(' AND '),
		tempParams: tempParams,
	};
}

function update() {
	const data = payload.get().body.toObject();
	// 验证data.tableName 和 data.columnName 只能有字母数字下划线
	if (!/^[a-zA-Z0-9_]+$/.test(data.tableName) || !/^[a-zA-Z0-9_]+$/.test(data.columnName) || !/^[a-zA-Z0-9_]+$/.test(data.dbName)) {
		return errMsg(405, '不支持的数据');
	}

	delete data.createTime;
	delete data.updateTime;
	const newData = {};
	Object.keys(data).forEach((item) => {
		newData[camelToUnderscore(item)] = data[item];
	});
	let filter = payload.get().path.split('/').pop();
	const columnsArr = Object.keys(newData);
	let dataArr = [];
	const placeholders = [];
	columnsArr.forEach((item) => {
		if (newData[item]) {
			placeholders.push(`${item} = ?`);
			dataArr.push(newData[item]);
		} else {
			placeholders.push(`${item} = NULL`);
		}
	});
	const newPlaceholders = placeholders.join(',');
	const query = `UPDATE ${TABLE_NAME} SET ${newPlaceholders}, update_time = NOW() WHERE ${COLUMN_KEY} = ?`;

	const res = SQL.exec('system_sql', query, ...[...dataArr, filter]);
	if (res) {
		return okMsg(res);
	}
	return errMsg(507, '更新失败');
}

function main() {
	// 验证用户权限
	'use api/user/acl/excerpt.js'

	switch (payload.get().method) {
		case 'GET':
			return sql_select();
		case 'PUT':
			return update();
		case 'DELETE':
			return sql_delete();
		default:
			response.status.notFound();
			return `404 page not found`;
	}
}
